//
//  JDChangePhoneNumViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/5/15.
//

import UIKit
/// 修改手机号码
class JDChangePhoneNumViewController: JDBaseViewController {

    var changePhoneNumCompleted: ((String)->Void)?
    var bottomContainerView: UIView?
    var cancelButton: UIButton?
    var confirmButton: UIButton?
    
    var phoneImgV: UIImageView?
    var phoneTitle: UILabel?
    var phoneNumber: UILabel?
    var inputContainerView: UIView?
    var newPhoneNumInputView: UITextField?
    var validCodeInputView: UITextField?
    
    var validCodeLeftView: JDPaddingLabel?
    var sendValidCodeButton: UIButton?
    
    var countDownTimer: Timer?
    var countNumber = 60
    
    var changePhoneCompleted: ((String)->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupNavigationTitle("更换手机号")
        self.setupLeftBackItem()
    }

    func setupUIElements() {

        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(104)
        })
        self.bottomContainerView?.backgroundColor = .white

        self.cancelButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.cancelButton!)
        self.cancelButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomContainerView!.snp.centerX).offset(-5)
            make.centerY.equalTo(self.bottomContainerView!)
            make.left.equalTo(self.bottomContainerView!).offset(12)
            make.height.equalTo(54)
        })
        self.cancelButton?.layer.cornerRadius = 27
        self.cancelButton?.backgroundColor = color("#F5F6F8")
        self.cancelButton?.setTitle("返回", for: .normal)
        self.cancelButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.cancelButton?.setTitleColor(.black, for: .normal)
        self.cancelButton?.addTarget(self, action: #selector(backAction), for: .touchUpInside)
        
        self.confirmButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.confirmButton!)
        self.confirmButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.bottomContainerView!.snp.centerX).offset(5)
            make.right.equalTo(self.bottomContainerView!).offset(-12)
            make.height.equalTo(54)
            make.centerY.equalTo(self.bottomContainerView!)
        })
        self.confirmButton?.setTitle("确定", for: .normal)
        self.confirmButton?.backgroundColor = color("#FA6161")
        self.confirmButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.confirmButton?.setTitleColor(.white, for: .normal)
        self.confirmButton?.layer.cornerRadius = 27
        self.confirmButton?.addTarget(self, action: #selector(changePhoneNumAction), for: .touchUpInside)
     
        self.phoneImgV = UIImageView()
        self.view.addSubview(self.phoneImgV!)
        self.phoneImgV?.snp.makeConstraints({ make in
            make.left.equalTo(self.view).offset(30)
            make.top.equalTo(self.view).offset(26+statusBarHeight+44)
            make.size.equalTo(CGSize(width: 38, height: 38))
        })
        self.phoneImgV?.image = UIImage(named: "phone_image")?.withRenderingMode(.alwaysOriginal)
        self.phoneImgV?.contentMode = .scaleAspectFit

        self.phoneTitle = UILabel()
        self.view.addSubview(self.phoneTitle!)
        self.phoneTitle?.snp.makeConstraints({ make in
            make.left.equalTo(self.phoneImgV!.snp.right).offset(7)
            make.top.equalTo(self.phoneImgV!).offset(-2)
            make.height.equalTo(17)
        })
        self.phoneTitle?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#000143"), numberOfLines: 1)
        self.phoneTitle?.text = "登录时记录吧"
        
        self.phoneNumber = UILabel()
        self.view.addSubview(self.phoneNumber!)
        self.phoneNumber?.snp.makeConstraints({ make in
            make.left.equalTo(self.phoneTitle!)
            make.top.equalTo(self.phoneTitle!.snp.bottom).offset(1)
            make.height.equalTo(25)
        })
        self.phoneNumber?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 18, weight: .semibold), textColor: color("#000143"))
        self.phoneNumber?.text = JDLoginModel.default.mobile?.hidePhoneNumber()
        
        self.inputContainerView = UIView()
        self.view.addSubview(self.inputContainerView!)
        self.inputContainerView?.snp.makeConstraints({ make in
            make.left.equalTo(self.view).offset(12)
            make.right.equalTo(self.view).offset(-12)
            make.top.equalTo(self.phoneImgV!.snp.bottom).offset(18)
            make.height.equalTo(58+1+58)
        })
        self.inputContainerView?.layer.cornerRadius = 8
        self.inputContainerView?.backgroundColor = .white
        self.inputContainerView?.clipsToBounds = true
        
        self.newPhoneNumInputView = UITextField()
        self.inputContainerView?.addSubview(self.newPhoneNumInputView!)
        self.newPhoneNumInputView?.snp.makeConstraints({ make in
            make.left.right.top.equalTo(self.inputContainerView!)
            make.height.equalTo(58)
        })
        self.newPhoneNumInputView?.placeholder = "输入新的手机号码"
        self.newPhoneNumInputView?.textColor = color("#333333")
        self.newPhoneNumInputView?.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        self.newPhoneNumInputView?.backgroundColor = .white
        
        let phoneNumLeftView = JDPaddingLabel(frame: CGRect(x: 0, y: 0, width: 77, height: 58))
        phoneNumLeftView.edgeInsets = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 20)
        phoneNumLeftView.text = "新手机"
        phoneNumLeftView.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 15, weight: .medium), textColor: color("#333333"), numberOfLines: 1)
        self.newPhoneNumInputView?.leftView = phoneNumLeftView
        self.newPhoneNumInputView?.leftViewMode = .always
        
        let line = UIView()
        self.inputContainerView?.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalTo(self.inputContainerView!).offset(12)
            make.right.equalTo(self.inputContainerView!).offset(-12)
            make.top.equalTo(self.newPhoneNumInputView!.snp.bottom)
            make.height.equalTo(1)
        }
        line.backgroundColor = color("#F5F6F8")
        
        self.sendValidCodeButton = UIButton(type: .custom)
        self.inputContainerView?.addSubview(self.sendValidCodeButton!)
        self.sendValidCodeButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.inputContainerView!).offset(-12)
            make.size.equalTo(CGSize(width: 103, height: 38))
            make.top.equalTo(line.snp.bottom).offset(10)
        })
        self.sendValidCodeButton?.layer.cornerRadius = 4
        self.sendValidCodeButton?.layer.borderWidth = 0.5
        self.sendValidCodeButton?.layer.borderColor = color("#FA6161").cgColor
        self.sendValidCodeButton?.setTitle("获取验证码", for: .normal)
        self.sendValidCodeButton?.setTitleColor(color("#FA6161"), for: .normal)
        self.sendValidCodeButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.sendValidCodeButton?.addTarget(self, action: #selector(sendValidCodeAction), for: .touchUpInside)
        
        self.validCodeInputView = UITextField()
        self.inputContainerView?.addSubview(self.validCodeInputView!)
        self.validCodeInputView?.snp.makeConstraints({ make in
            make.left.bottom.equalTo(self.inputContainerView!)
            make.right.equalTo(self.sendValidCodeButton!.snp.left).offset(-5)
            make.top.equalTo(line.snp.bottom)
        })
        self.validCodeInputView?.placeholder = "输入验证码"
        self.validCodeInputView?.textColor = color("#333333")
        self.validCodeInputView?.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        self.validCodeInputView?.backgroundColor = .white
        self.validCodeInputView?.clearButtonMode = .always
        
        self.validCodeLeftView = JDPaddingLabel(frame: CGRect(x: 0, y: 0, width: 77, height: 58))
        self.validCodeLeftView?.edgeInsets = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 20)
        self.validCodeLeftView?.text = "验证码"
        self.validCodeLeftView?.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 15, weight: .medium), textColor: color("#333333"), numberOfLines: 1)
        self.validCodeInputView?.leftView = self.validCodeLeftView
        self.validCodeInputView?.leftViewMode = .always
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    @objc func sendValidCodeAction() {
        if self.countDownTimer != nil {
            return
        }
        
        var params = [String: Any]()
        params["mobile"] = self.newPhoneNumInputView?.text

        JDNetWorkRequest(.getVerificationCode(params)) { responseStr in
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                printLog("倒计时")
                self.view.toast(message: "发送成功")
                
                self.countDownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timeCountDown), userInfo: nil, repeats: true)
                self.countDownTimer?.fire()
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
    @objc func changePhoneNumAction() {
        
        var params = [String: Any]()
        params["mobile"] = self.newPhoneNumInputView?.text
        params["smsCode"] = self.validCodeInputView?.text
        
        JDNetWorkRequest(.changeMobile(params)) { responseStr in
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                self.countDownTimer?.invalidate()
                self.countDownTimer = nil
                self.countNumber = 60
                printLog("修改成功")
                JDLoginModel.default.mobile = self.newPhoneNumInputView?.text
                self.backAction()
                self.changePhoneCompleted?(self.newPhoneNumInputView?.text ?? "")
            } else {
                printLog("修改失败")
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
    @objc func timeCountDown() {
            if self.countNumber > 0 {
                self.countNumber -= 1
                self.sendValidCodeButton?.setTitle("(\(self.countNumber)s)", for: .normal)
                
            } else {
                self.countDownTimer?.invalidate()
                self.countDownTimer = nil
                self.countNumber = 60
                self.sendValidCodeButton?.setTitle("获取验证码", for: .normal)
            }
        }

}
